package com.ctw.mapmycity;

import java.util.Locale;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.ctw.mapmycity.auth.AuthenticatorUtil;
import com.ctw.mapmycity.auth.LoginActivity;
import com.ctw.mapmycity.model.MenuItemModel;
import com.ctw.mapmycity.util.MaskUtil;
import com.facebook.Session;

public class MenuActivity extends Activity {

	private AccountManager mAccountManager;

	private MapActivity mapCityFrag;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;

	// Progress manager
	private MaskUtil maskUtil;
	private View mContentView;
	
	public void checkUserLogin() {
		
		// try to open session if it's cached
		Session.openActiveSessionFromCache(getApplicationContext());
		
		mAccountManager = AccountManager.get(getApplicationContext());
		Account[] accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);

		if (accounts.length < 1){
			closeFaceBookSession();
			
			Intent i = new Intent(getApplicationContext(), LoginActivity.class);
			startActivity(i);
			return;
		}

		new AsyncTask<Account, Void, Bundle>() {
			@Override
			protected void onPreExecute() {
				maskUtil.mask(mContentView, R.string.login_progress_signing_in);
			}

			@Override
			protected Bundle doInBackground(Account... acc) {
				return new AuthenticatorUtil(
						MenuActivity.this.getApplication().getApplicationContext()).getAuthToken(acc[0], Constants.AUTHTOKEN_TYPE, null);
			}

			@Override
			protected void onPostExecute(final Bundle result) {
				maskUtil.unmask(mContentView);

				Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
				if (intent != null){
					startActivity(intent);
					return;
				}
				
				((MapMyCity) MenuActivity.this.getApplication()).setLoggedAccount((Account) result.getParcelable("account"));
			}

			@Override
			protected void onCancelled() {
				MenuActivity.this.finish();
			}
		}.execute(accounts);
	}

	private void closeFaceBookSession(){
		Session fbSession = Session.getActiveSession();
		if (fbSession != null && fbSession.isOpened()){
			Session.getActiveSession().closeAndClearTokenInformation();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		// Progress manager
		maskUtil = new MaskUtil(this);
		mContentView = this.findViewById(R.id.drawer_layout);

		// enable ActionBar app icon to behave as action to toggle nav drawer
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		
		getActionBar().hide();

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
		
		_initMenu();

		mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawerLayout);
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(
				this,                  /* host Activity */
				mDrawerLayout,         /* DrawerLayout object */
				R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
				R.string.drawer_open,  /* "open drawer" description for accessibility */
				R.string.drawer_close  /* "close drawer" description for accessibility */
				) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
			}
		};
		
		
            selectItem(1);
		
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		
		  
		
	}

	private void _initMenu() {
		MenuAdapter mAdapter = new MenuAdapter(this);
		
		// Add Header
		mAdapter.addHeader(R.string.ns_menu_main_header);
		String[] mListMenu = getResources().getStringArray(R.array.ns_menu_items);
		String[] menuItemsIcon = getResources().getStringArray(R.array.ns_menu_items_icon);
		addMenuItems(mAdapter, mListMenu, menuItemsIcon, true);
//		
		mAdapter.addHeader(R.string.ns_menu_sync);
		mListMenu = getResources().getStringArray(R.array.ns_menu_sync_items);
		menuItemsIcon = getResources().getStringArray(R.array.ns_menu_sync_items_icon);
		addMenuItems(mAdapter, mListMenu, menuItemsIcon, false);		
		
		mAdapter.addHeader(R.string.ns_menu_config);
		mListMenu = getResources().getStringArray(R.array.ns_menu_config_items);
		menuItemsIcon = getResources().getStringArray(R.array.ns_menu_config_items_icon);
		addMenuItems(mAdapter, mListMenu, menuItemsIcon, false);		
		
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		if (mDrawerList != null)
			mDrawerList.setAdapter(mAdapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

	}
	
	private void addMenuItems(MenuAdapter mAdapter, String[] mListMenu, String[] menuItemsIcon, boolean showCounter){
		int res = 0;
		for (String item : mListMenu) {
			int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
			int id_icon = getResources().getIdentifier(menuItemsIcon[res], "drawable", this.getPackageName());

			MenuItemModel mItem = new MenuItemModel(id_title, id_icon);
			mItem.setShowCounter(showCounter);
			mAdapter.addItem(mItem);
			res++;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		super.onResume();

		// check logged user
		checkUserLogin();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	    
		Session session = Session.getActiveSession();
		if (session != null)
			session.onActivityResult(this, requestCode, resultCode, data);
	}
	
	@Override
	public void onBackPressed() {
		
		if (mapCityFrag.layoutRegisterForm.getVisibility() != View.GONE){
			
			if (mapCityFrag.sliding_layout.isExpanded())
				mapCityFrag.changeSlidingStatusLayout();
			
			mapCityFrag.layoutRegisterForm.setVisibility(View.GONE);
			
			if (mapCityFrag.currentMarkerFound != null)
				mapCityFrag.currentMarkerFound.setVisible(false);
		
		} else {
			this.moveTaskToBack(true);	
		}
		
		// TODO FIND A WAY TO IMPLEMENT BACK PER FRAGMENT
//		super.onStop();
//		super.onBackPressed();
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content view
		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		// Handle action buttons
		switch(item.getItemId()) {
		case R.id.action_websearch:

			// create intent to perform web search for this planet
			Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
			intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());

			// catch event that there's no activity to handle intent
			if (intent.resolveActivity(getPackageManager()) != null) {
				startActivity(intent);
			} else {
				Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
			}

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
		public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
			super(
					mActivity,
					mDrawerLayout, 
					R.drawable.ic_drawer,
					R.string.ns_menu_open, 
					R.string.ns_menu_close);
		}

		@Override
		public void onDrawerClosed(View view) {
			getActionBar().setTitle(getString(R.string.ns_menu_close));
			invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
		}

		@Override
		public void onDrawerOpened(View drawerView) {
			getActionBar().setTitle(getString(R.string.ns_menu_open));
			invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
		}
	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			selectItem(position);
		}
	}

	private void selectItem(int position) {
		FragmentTransaction transaction = getFragmentManager().beginTransaction();

		switch (position) {
			case 1 : 
				if (mapCityFrag == null)
					mapCityFrag = new MapActivity();

				transaction.replace(R.id.content_frame, mapCityFrag);
				break;
			case 10 :
				
				Account[] accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
				if (accounts.length > 0){
					mAccountManager.removeAccount(accounts[0], null, new Handler());
				}
				
				closeFaceBookSession();

				Intent i = new Intent(getApplicationContext(), LoginActivity.class);
				startActivity(i);
				return;
				
			default :
/*				PlanetFragment fragment = new PlanetFragment();
				Bundle args = new Bundle();
				args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
				fragment.setArguments(args);

				transaction.replace(R.id.content_frame, fragment);
*/		}


		transaction.addToBackStack(null);
		transaction.commit();

		// update selected item and title, then close the drawer
//		mDrawerList.setItemChecked(position, true);
//		setTitle(getResources().getIdentifier(mListMenu[position - 1], "string", this.getPackageName()));
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	/**
	 * Fragment that appears in the "content_frame", shows a planet
	 */
	public static class PlanetFragment extends Fragment {
		public static final String ARG_PLANET_NUMBER = "planet_number";

		public PlanetFragment() {

			// Empty constructor required for fragment subclasses
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
			int i = getArguments().getInt(ARG_PLANET_NUMBER);
			String planet = getResources().getStringArray(R.array.menuitens_array)[i];
			int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
					"drawable", getActivity().getPackageName());
			((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
			getActivity().setTitle(planet);
			return rootView;
		}
	}
}